package com.lqq.dao.impl;

import java.util.Set;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;

import com.lqq.dao.UserDAO;
import com.lqq.entity.Orders;
import com.lqq.entity.Users;

public class UserDAOImpl implements UserDAO {

	SessionFactory sessionFactory;
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	@Override
	public boolean checkLogin(Users users) {
		// TODO Auto-generated method stub
		Session session = sessionFactory.getCurrentSession();
		Criteria criteria = session.createCriteria(Users.class);
		criteria.add(Restrictions.eq("loginName", users.getLoginName()));
		criteria.add(Restrictions.eq("loginPassword",users.getLoginPassword()));
		if(criteria.list().size() > 0){
			return true;
		}
		return false;
	}

	@Override
	public Set<Orders> getAllOrders(Integer userId) {
		// TODO Auto-generated method stub
		Session session = sessionFactory.getCurrentSession();
		Users users = (Users) session.get(Users.class, userId);
		Set<Orders> orders =  users.getOrderses();
		return orders;
		
	}

	@Override
	public boolean loginNameIsExist(String loginName) {
		// TODO Auto-generated method stub
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("FROM Users WHERE loginName='"+loginName+"'");
		if(query.list().size() > 0){
			return true;
		}
		return false;
	}

	@Override
	public Users getUserByLoginName(String loginName) {
		// TODO Auto-generated method stub
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("FROM Users WHERE loginName='"+loginName+"'");
		Users users = (Users) query.list().iterator().next();
		
		return users;
	}

	@Override
	public boolean updataUserinfo(Integer userId, String loginName, String realName, String email, String phone,String address) {
		// TODO Auto-generated method stub
		try {
			Session session = sessionFactory.getCurrentSession();
			String sql = "UPDATE Users SET loginName='"+loginName+"',"+
							"realName='"+realName+"',"+
							"email='"+email+"',"+
							"phone='"+phone+"',"+
							"address='"+address+"'"+
							" WHERE userId="+userId;
			Query query = session.createQuery(sql);
			int i = query.executeUpdate();
			if(i > 0 ){
				System.out.println("OK");
				return true;
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public void addUser(Users user) {
		// TODO Auto-generated method stub
		Session session = sessionFactory.getCurrentSession();
		session.save(user);
	}

	

	
}
